<template>
    <div class="header">
        <div class="title">请选择直播商品</div>
        <el-button size="small" :icon="ArrowLeftBold">返回</el-button>
    </div>
    <div class="grid-box">
        <div class="left-box">
            <el-row class="left-row" justify="space-between" align="middle">
                <el-col :span="6">
                    商品库
                </el-col>
                <el-col :span="5" class="flex-col">
                    <span class="btn">新增商品</span>
                    <span class="btn">导入商品</span>
                </el-col>
            </el-row>
            <el-row class="left-row" align="middle">
                <el-col :span="6">
                    <el-checkbox v-model="checkAll" @change="checkAllFn">全选</el-checkbox>
                </el-col>
            </el-row>
            <!-- <el-button @click="toSimulatedPage">生成默认话术音频</el-button> -->
            <div class="goods-box">
                <div v-for="(item, index) in goodsList" :key="index" class="goods-list">
                    <div class="goods-checkbox">
                        <el-checkbox v-model="item.checked" @change="goodsCheckedChange(item)"></el-checkbox>
                    </div>
                    <div class="goods-content">
                        <img class="left" :src="item.imgSrc" width="80px" height="80px"></img>
                        <div class="right">
                            <div class="right-name">{{ item.name }}</div>
                            <el-row align="middle" justify="start">
                                <div class="line-through">原价：{{ formatPrice(item.originPrice) }}元</div>
                                <div>售价：{{ formatPrice(item.actualPrice) }}元</div>
                            </el-row>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="right-box">
            <h3>直播商品</h3>
            <div class="goods-box">
                <div v-for="(item, index) in checkedGoods" :key="index" class="goods-list">
                    <div class="goods-checkbox">
                        <el-checkbox v-model="item.checked"></el-checkbox>
                    </div>
                    <div class="goods-content">
                        <img class="left" :src="item.imgSrc" width="80px" height="80px"></img>
                        <div class="right">
                            <div class="right-name">{{ item.name }}</div>
                            <el-row align="middle" justify="start">
                                <div class="line-through">原价：{{ formatPrice(item.originPrice) }}元</div>
                                <div>售价：{{ formatPrice(item.actualPrice) }}元</div>
                            </el-row>
                            <el-row justify="space-between" align="middle" style="width:100%">
                                <el-checkbox v-model="item.isExplain" :disabled="!item.checked">讲解商品</el-checkbox>
                                <el-row style="width:60%" align="middle">
                                    <el-col :span="6">
                                        <el-icon>
                                            <Edit />
                                        </el-icon>
                                        <span>编辑</span>
                                    </el-col>
                                    <el-col :span="6">
                                        <el-icon>
                                            <Top />
                                        </el-icon>
                                        <span>上移</span>
                                    </el-col>
                                    <el-col :span="6">
                                        <el-icon>
                                            <Bottom />
                                        </el-icon>
                                        <span>下移</span>
                                    </el-col>
                                </el-row>
                            </el-row>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <el-row justify="end" align="middle">
        <el-button size="small" type="primary" @click="showDialog">智能生成直播间</el-button>
    </el-row>
    <el-dialog title="智能生成直播间" v-model="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="false" >
        <div v-loading="scriptLoading">
            <el-row>
                <el-col :span="6">
                    <h2>直播话术</h2>
                    <div>生成完成</div>
                </el-col>
                <el-col :span="6">
                    <h2>直播互动</h2>
                    <div>生成完成</div>
                </el-col>
                <el-col :span="6">
                    <h2>直播场景</h2>
                    <div>生成完成</div>
                </el-col>
                <el-col :span="6">
                    <h2>直播策略</h2>
                    <div>生成完成</div>
                </el-col>
            </el-row>
        </div>
        <el-row justify="center">
            <el-button type="primary" @click="toSimulatedPage" :loading="scriptLoading">模拟直播</el-button>
            <el-button type="primary" @click="toSetPage">直播间设置</el-button>
        </el-row>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from "element-plus";
import { Edit, Top, Bottom } from '@element-plus/icons-vue'
import { getLifeGoods, explainGoods } from '@/api/douyin'
import { generateDefaultScript, textToAudio } from '@/api/common'
import { ArrowLeftBold } from "@element-plus/icons-vue";
import { useRouter } from 'vue-router'
import { useAppStore } from "@/store/index"

const router = useRouter()
const store = useAppStore()

const checkAll = ref(false)
const dialogVisible = ref(false)
const scriptLoading = ref(false)
const goodsList = ref([])
const checkedGoods = ref([])

const checkAllFn = () => {
    goodsList.value.forEach((item) => {
        item.checked = checkAll.value
    })

    checkedGoods.value = goodsList.value.filter((item) => item.checked)
}

const goodsCheckedChange = (item) => {
    if(item.checked){
        checkedGoods.value.push(item)
    }else{
        checkedGoods.value = checkedGoods.value.filter((goods) => goods.id !== item.id)
    }
}
// 获取商品信息
const getGoodsList = async () => {
    const rst = await getLifeGoods()
    console.log('[getGoodsList] rst:', rst)
    goodsList.value = rst.card_list.map(item => {
        return {
            id: item.product_base_info.product_id,
            appName: item.product_base_info.app_name,
            name: item.product_base_info.name,
            originPrice: item.price_info.origin_price,
            actualPrice: item.price_info.actual_price,
            imgSrc: item.product_base_info.image_info[0].web_url,
            checked: false,
            isExplain: false, // 是否需要讲解
        }
    })
    console.log('[getGoodsList] goodsList:', goodsList.value)
}

const showDialog = () => {
    console.log('[showDialog]:')
    checkedGoods.value = goodsList.value.filter(item => item.checked)

    if (checkedGoods.value.length) {
        dialogVisible.value = true
        getDefaultText()
    } else {
        ElMessage.error("至少选择一个商品！")
    }
}

const getDefaultText = async () => {
    try {
        const goodsItem = checkedGoods.value[0]
        const goodsDesc =
            `您是一位充满活力和热情的直播主播，请根据以下要求和产品介绍，编写一段吸引人的真实带货话术。话术要求：1.避免使用“结束直播”或者“下播”或者“离开直播间”的直接措辞，避免使用表示告别的常用短语，避免暗示直播结束的任何用语；2.话术结尾以【家人们！感谢大家一直陪伴着我们直播间啊！我们会继续努力为大家带来更多好物和惊喜的！千万不要离开直播间哦！】结束，可以对这段话进行改写，和上文自然衔接；3.请确保生成的内容中不包含任何形式的括号，包括小括号（()）、中括号（[]）和大括号（{ }）；4.亲切地称呼观众为【家人们】，以增强亲切感和归属感；5.避免使用【早上好】、【中午好】、【晚上好】等具体时间问候语，以适应不同时间段的直播；我们直播间每天都会为大家带来各种好物和优惠活动，相信总有一款会让你心动的。所以，赶紧关注我们吧！”结尾。6.围绕产品介绍，编写一篇约1500字左右的直播话术，销售风格。7.话术不能包含极限词，如第一，唯一，独一，首个，首选，首发，领袖，巅峰，最高等词、广告违禁词如一盒见效、彻底康复等词。8.话术不能包含秒杀，送礼品等诱导消费的词语。`;
        const params = {
            // model: "deepseek-chat",
            // model: "ernie-lite-8k",
            // max_tokens: 2048,
            // temperature: 1.3,
            messages: [
                {
                    role: "user",
                    content: goodsDesc + formatGoodsDesc(goodsItem),
                },
            ],
        }
        console.log('params', params)
        scriptLoading.value = true
        console.log('开始生成话术------', new Date())

        const { choices } = await generateDefaultScript(params)
        console.log('[getDefaultText] rst:', choices)
        const text = choices.map((item) => item.message.content).join(",");
        // console.log('[getDefaultText] rst:', text)
        console.log('生成话术完成------', new Date())
        store.updateState({
            defaultScriptText: text
        })
        checkedGoods.value = goodsList.value.filter(item => item.checked)
        await getDefaultAudio(text || store.state.defaultScriptText, checkedGoods.value[0])
        scriptLoading.value = false

    } catch (error) {
        scriptLoading.value = false
        console.error("Error:", error);
    }
}

// 生成默认话术音频
const getDefaultAudio = async (text, goodsItem) => {
    const params = {
        models_name: "meiqi", // 声音模型
        audio_save_path: "D:", // 保存路径
        audio_save_filename: goodsItem.id + ".wav", // 保存文件名
        text: text, // 文本内容
        length_scale: 1.1, // 语速
        comma_pause: 0.3, // 逗号停顿
        period_pause: 0.5, // 句号停顿
        priority: 1, //0是代表高级 1是代表低级 默认是1
    }

    try {
        console.log('生成默认话术音频----', new Date())
        const rst = await textToAudio(params)
        store.updateState({
            defaultAudio: rst.audio_path
        })
        console.log('生成默认话术完成----', new Date())
        console.log('[getDefaultAudio] rst:', rst.audio_path)
       
    } catch (error) {
        console.log("getDefaultAudio", error)
    }

}

const formatGoodsDesc = (goodsItem) => {
    return `产品介绍：产品名：${goodsItem.name},直播间专属价格${(goodsItem.actualPrice / 100).toFixed(2)}元,市场价:${(goodsItem.originPrice / 100).toFixed(2)}元,适用人群：男女通用`
}

const formatPrice = (price) => {
    return (price / 100).toFixed(2)
}

const toSetPage = () => {
    router.push({
        name: 'LiveRoomSet'
    })
}

const toSimulatedPage = () => {
    console.log('toSimulatedPage');
    // checkedGoods.value = goodsList.value.filter(item => item.checked)
    // getDefaultAudio(store.state.defaultScriptText, checkedGoods.value[0])
    router.push({
        name: 'SimulatedLive'
    })
    
}

onMounted(() => {
    getGoodsList()
})
</script>

<style lang="less" scoped>
.header {
    width: 100%;
    height: 50px;
    background-color: @bg-default;
    color: @font-color-default;
    display: flex;
    align-items: center;
    padding-left: 20px;
    box-sizing: border-box;
    margin-bottom: 20px;
    padding-right: 20px;

    .title {
        flex: 1;
        flex-shrink: 0;
        color: @color-white;
        text-align: center;
    }
}

.grid-box {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 20px;
    box-sizing: border-box;
    overflow: hidden;

    .left-box,
    .right-box {
        background-color: @bg-default;
        padding: 0 20px;
        box-sizing: border-box;
        overflow: hidden;

        .left-row {
            padding: 10px 0 0px 0;
            color: @color-white;
        }

        .flex-col {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .btn {
                color: @btn-color;
                cursor: pointer;
                font-size: 12px;
            }
        }
    }

    .goods-box {
        height: calc(100vh - 280px);
        overflow-y: auto;
        overflow-x: hidden;
        color: @color-white !important;

        /* 滚动条整体部分 */
        &::-webkit-scrollbar {
            width: 5px;
            /* 滚动条宽度 */
            height: 5px;
            /* 滚动条高度 */
        }

        /* 滚动条滑块 */
        &::-webkit-scrollbar-thumb {
            background: #eee;
            /* 滑块颜色 */
            border-radius: 10px;
            /* 滑块圆角 */
        }

        /* 滚动条轨道 */
        &::-webkit-scrollbar-track {
            background: transparent;
            /* 轨道颜色 */
        }

        .goods-list {
            display: flex;
            margin-bottom: 20px;

            .goods-checkbox {
                display: flex;
                align-items: center;
            }

            .goods-content {
                display: flex;
                width: 100%;

                .line-through {
                    text-decoration: line-through;
                    margin-right: 20px;
                }

                .left {
                    margin: 0 10px;
                }

                .right {
                    width: 100%;
                    display: flex;
                    flex-direction: column;
                    align-items: flex-start;

                    .right-name {
                        width: calc(100% - 100px);
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }
            }
        }
    }

}
</style>